package com.authoritydemo.controller;

import com.authoritydemo.entity.Users;
import com.authoritydemo.service.UsersService;
import com.authoritydemo.vo.UserProfileVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/user")
public class UserController {


    @Autowired
    private UsersService usersService;

    /**
     * 存在水平越权漏洞的接口：
     * - 必须登录才能访问
     * - 允许查看任意用户的信息（只要知道 ID）
     */
    @GetMapping("/profile/{userId}")
    public String getUserProfile(@PathVariable Long userId,
                                 HttpSession session,
                                 Model model) {
        // 1. 检查是否登录
        Users currentUser = (Users) session.getAttribute("user");
        if (currentUser == null) {
            return "login";
        }

        // 2. 获取目标用户信息
        Users targetUser = usersService.getById(userId);

        if (targetUser == null) {
            model.addAttribute("error", "用户不存在");
            return "user-not-found"; // 对应 templates/user-not-found.html
        }

//        // 3. 校验逻辑：只能查看自己的信息 或者 具有管理员权限
//        if (!currentUser.getId().equals(targetUser.getId()) && !"ADMIN".equals(currentUser.getRole())) {
//            model.addAttribute("error", "无权访问他人信息");
//            return "forbidden"; // 对应 templates/forbidden.html
//        }

        // 4. 构造 VO 对象，仅返回公开字段
        UserProfileVO userProfileVO = new UserProfileVO();
        userProfileVO.setId(targetUser.getId());
        userProfileVO.setUsername(targetUser.getUsername());
        userProfileVO.setNickname(targetUser.getNickname());
        userProfileVO.setEmail(targetUser.getEmail());
        System.out.println(userProfileVO);

        model.addAttribute("user", userProfileVO);
        return "user-profile"; // 对应 templates/user-profile.html
    }
}